package cn.tedu.hotelApi.base.captchaGenerator;

import cn.tedu.hotelApi.base.utils.CacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/api") // 在类级别设置基础路径，使得所有方法的路径都可以相对简化
public class CaptchaController {
    //注入缓存工具类
    @Autowired
    CacheUtils cacheUtils;
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int WIDTH = 200;
    private static final int HEIGHT = 60;
    private static final int CODE_LENGTH = 4;
    private static final int CHARACTER_SPACING = 10;

    public static Map<String, Object> generateCaptchaImage() throws IOException {
        // 1. 创建BufferedImage对象
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

        // 2. 获取Graphics2D对象
        Graphics2D graphics = image.createGraphics();

        // 3. 设置背景色和干扰元素
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, WIDTH, HEIGHT);
        Random random = new Random();
        for (int i = 0; i < 50; i++) {
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            int size = random.nextInt(3);
            graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            graphics.drawOval(x, y, size, size);
        }
        // 4. 生成验证码字符串
        StringBuilder sb = new StringBuilder(CODE_LENGTH);
        for (int i = 0; i < CODE_LENGTH; i++) {
            sb.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
        }
        String captchaCode = sb.toString(); // 生成验证码字符串

        // 5. 绘制验证码字符
        Font font = new Font("Arial", Font.BOLD, 90);
        FontRenderContext context = graphics.getFontRenderContext();
        AffineTransform transform = AffineTransform.getTranslateInstance(20, 20);
        transform.scale(0.5, 0.5);
        graphics.setFont(font.deriveFont(transform));
        for (int i = 0; i < CODE_LENGTH; i++) {
            char c = captchaCode.charAt(i);
            graphics.setColor(getRandomColor());
            // 调整这里的x坐标计算，引入字符间隔
            int x = 30 + i * (30 + CHARACTER_SPACING);
            // 修改：30是起始位置，30是字符宽度，CHARACTER_SPACING是新增的间隔
            graphics.drawString(String.valueOf(c), x, 40);
//            graphics.drawString(String.valueOf(c), 30 + i * 30, 40);
        }

        // 输出图片和验证码字符串
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        byte[] captchaImageBytes = baos.toByteArray();

        Map<String, Object> result = new HashMap<>();
        result.put("captchaCode", captchaCode);
        result.put("imageBytes", captchaImageBytes);
        return result;
    }

    @GetMapping(value = "/captcha", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, Object>> generateAndReturnCaptchaData(HttpSession session) throws IOException {
        Map<String, Object> captchaData = generateCaptchaImage();
        String captchaCode = (String) captchaData.get("captchaCode");
        byte[] captchaImageBytes = (byte[]) captchaData.get("imageBytes");
        System.out.println(captchaCode + "验证码");
        cacheUtils.set("captcha", captchaCode);
        // 将图片转换为Base64字符串以便于JSON传输
        String base64Image = Base64.getEncoder().encodeToString(captchaImageBytes);

        Map<String, Object> response = new HashMap<>();
        response.put("captchaCode", captchaCode);
        response.put("image", base64Image);

        return new ResponseEntity<>(response, HttpStatus.OK);
    }
    private static Color getRandomColor() {
        Random random = new Random();
        return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
    }

}